package com.yuexun.dhdoctor.module.Contract.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.Contract.adapter.AddMemberAdapter;
import com.yuexun.dhdoctor.module.Contract.adapter.CreateGroupAdapter;
import com.yuexun.dhdoctor.module.Contract.bean.DepartOrPeopleData;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.Contract.bean.PeopleBean;
import com.yuexun.dhdoctor.module.Contract.model.impl.PeopleModel;
import com.yuexun.dhdoctor.module.Contract.presenter.impl.PeoplePresenter;
import com.yuexun.dhdoctor.module.Contract.ui.view.IPeopleView;
import com.yuexun.dhdoctor.widget.EmptyLayout;
import com.yuexun.dhdoctor.widget.PullToRefresh.PullToRefreshBase;
import com.yuexun.dhdoctor.widget.PullToRefresh.PullToRefreshList;

import org.kymjs.kjframe.KJDB;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by work-jx on 2016/7/21.
 */
public class Act_AddMember extends BaseKJActivity implements View.OnClickListener, IPeopleView {
    private ListView capitalListView;

    private String py[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
            "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
            "X", "Y", "Z"};

    private boolean locakScroll = false;

    private PullToRefreshList mPullRefreshListView;
    private EmptyLayout emptyLayout;
    private ListView lv;

    private TextView tvToast, addmember_sure_btn;

    private EditText etSearch;

    private ImageButton btnSearchClear;

    private AddMemberAdapter cAdapter;

    private ArrayAdapter<String> adapter1;

    private Handler handler;

    private int lastSelect = 0;

    private LayoutInflater mInflater;

    private int height;

//    private Context context;

    private View search_view;

    private LinearLayout searchLayout;

    private PeoplePresenter presenter;

    ArrayList<People> usersBeans_origin = new ArrayList<People>();

    GridView grid;
    CreateGroupAdapter adapter;

    private LinearLayout back;

    KJDB kjdb;
    ArrayList<People> datas;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_addmember);
        initView();
        handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 100:
                        tvToast.setVisibility(View.INVISIBLE);
                        break;
                    case 998: // 更新通讯录人员列表界面
//                        updateWidget();
                        break;
                    case 999: // 下拉刷新处理
                        if (mPullRefreshListView.isPullRefreshEnabled())
                            mPullRefreshListView.onPullDownRefreshComplete();
//                        updateWidget();
                        break;
                    case 10001: // 搜索有文字的的时候
                        btnSearchClear.setVisibility(View.VISIBLE);
                        capitalListView.setVisibility(View.GONE);
                        break;
                    case 10002: // 搜索没文字的的时候
                        btnSearchClear.setVisibility(View.INVISIBLE);
                        capitalListView.setVisibility(View.VISIBLE);
                        break;
                    case 10003://刷新底部
                        setGridView();
                        break;
                    case 10004:
                        break;
                    case 10005:
                        break;
                    default: // 默认消息处理
                        if (mPullRefreshListView.isPullRefreshEnabled())
                            mPullRefreshListView.onPullDownRefreshComplete();
                        if (msg.arg1 == 1)
//                            updateWidget();
                            break;
                }
            }
        };
    }

    void initView() {
        mInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        presenter = new PeoplePresenter(new PeopleModel(), this);
        tvToast = (TextView) findViewById(R.id.tvToast);

        grid = (GridView) findViewById(R.id.grid);

        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(this);

        btnSearchClear = (ImageButton) findViewById(R.id.btnSearchClear);
        btnSearchClear.setOnClickListener(this);

        addmember_sure_btn = (TextView) findViewById(R.id.addmember_sure_btn);
        addmember_sure_btn.setOnClickListener(this);

        searchLayout = (LinearLayout) findViewById(R.id.searchLayout);

        etSearch = (EditText) findViewById(R.id.etSearch2);
        etSearch.addTextChangedListener(new TextWatcher() {

            boolean hasPadding = true;

            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2,
                                      int arg3) {
                if (TextUtils.isEmpty(s) && !hasPadding) {
                    // search_view.setPadding(tenDip, tenDip, tenDip*4,
                    // tenDip);
                    Message msg = new Message();
                    msg.what = 10002;
                    handler.sendMessage(msg);

                    hasPadding = true;
                } else if (!TextUtils.isEmpty(s) && hasPadding) {
                    // search_view.setPadding(tenDip, tenDip, tenDip,
                    // tenDip);
                    Message msg = new Message();
                    msg.what = 10001;
                    handler.sendMessage(msg);

                    hasPadding = false;
                }
                if (cAdapter != null)
                    // cAdapter.getFilter().filter(s+"");
                {
                    cAdapter.getMyFilter(null == s ? "" : s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable arg0) {
                if (etSearch.getText().toString().length() == 0) {
                    searchLayout.setVisibility(View.VISIBLE);
                } else {
                    searchLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
            }
        });

        mPullRefreshListView = (PullToRefreshList) findViewById(R.id.lvContact);
        mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                initData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            }
        });
        emptyLayout = (EmptyLayout) findViewById(R.id.empty_layout);
        lv = mPullRefreshListView.getRefreshView();

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                People people = (People) arg0.getItemAtPosition(arg2);
                if (usersBeans_origin.contains(people)) {
                    usersBeans_origin.remove(people);
                    cAdapter.notifyDataSetChanged();
                    Message msg = new Message();
                    msg.what = 10003;
                    handler.sendMessage(msg);
                } else {
                    usersBeans_origin.add(people);
                    cAdapter.notifyDataSetChanged();
                    Message msg = new Message();
                    msg.what = 10003;
                    handler.sendMessage(msg);
                }
            }
        });
        // ----------------------
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {

            int current = 0;

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                if (locakScroll) {
                    return;
                }
                int firstPosition = 0;
                if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
//                    Logger.i(PublicFunction.TAG,
//                            "相等  " + lv.getLastVisiblePosition());
                    firstPosition = lv.getLastVisiblePosition();
                } else {
                    firstPosition = lv.getFirstVisiblePosition();
//                    Logger.i(PublicFunction.TAG,
//                            "不相等  " + lv.getLastVisiblePosition());
                }
                if (firstPosition == current) // 第一条显示的记录不变更
                {
                    return;
                }
                current = firstPosition;
                if (firstPosition < 0
                        || cAdapter.getItem(firstPosition) == null
                        || (((People) cAdapter.getItem(firstPosition))
                        .getPinyin()) == null
                        || "".equals(((People) cAdapter.getItem(firstPosition))
                        .getPinyin())) {
                    return;
                }
                int firstName = ((People) cAdapter.getItem(firstPosition))
                        .getPinyin().charAt(0);
                if ((lastSelect + 65) == firstName) {
                    return;
                }
                if (firstName >= 65 && firstName <= 90) {
                    TextView tvLast = (TextView) capitalListView
                            .getChildAt(lastSelect);
                    if (tvLast != null) {
                        tvLast.setBackgroundResource(0);
                    }
                    lastSelect = firstName - 65;
                    TextView tv = (TextView) capitalListView
                            .getChildAt(lastSelect);
                    if (tv == null) {
                        return;
                    }
                    tv.setBackgroundColor(0xffcce4ff);
                }
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
//                        ImageLoader.getInstance().lock();
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        locakScroll = false;
//                        ImageLoader.getInstance().unlock();
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
//                        ImageLoader.getInstance().lock();
                        break;
                    default:
                        break;
                }
            }
        });

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);

            }
        });

        // 显示右边的字母条,并设置点击事件
        capitalListView = (ListView) findViewById(R.id.lvScroll);
        // 设置listview被绘制的时候的监听事件，动态获取view的高度并相应调整每个字母间的距离
        ViewTreeObserver vto = capitalListView.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {

            @Override
            public boolean onPreDraw() {
                if (height == 0) {
//                    Logger.e(
//                            "lintest",
//                            "快捷listview高度----"
//                                    + capitalListView.getMeasuredHeight());
                    height = capitalListView.getMeasuredHeight() / 26;
                    capitalListView.setAdapter(adapter1);
                }
                return true;
            }
        });
        adapter1 = new ArrayAdapter<String>(this,
                android.R.layout.test_list_item, py) {

            @Override
            public synchronized View getView(int position, View convertView,
                                             ViewGroup parent) {
                // TODO 自动生成的方法存根
                Holder holder = null;
                if (convertView == null) {
                    convertView = mInflater.inflate(R.layout.scroll_list_item,
                            parent, false);
                    holder = new Holder();
                    ViewGroup.LayoutParams params = convertView.getLayoutParams();
                    params.height = height;
                    convertView.setLayoutParams(params);
                    holder.textView = (TextView) convertView
                            .findViewById(android.R.id.text1);
                    convertView.setTag(holder);

                } else {
                    holder = (Holder) convertView.getTag();
                }

                resetTextView(holder);
                if (lastSelect == position) {
                    holder.textView.setBackgroundColor(0xffcce4ff);
                } else {
                    holder.textView.setBackgroundResource(0);
                }
                holder.textView.setText(py[position]);
                // Logger.e("lintest", "---" + position + "-->" +
                // this.getItem(position) + "----");
                return convertView;
            }

            private void resetTextView(Holder holder) {
                holder.textView.setText(null);
            }

            class Holder {
                TextView textView;
            }

        };
        capitalListView.setOnTouchListener(pinyinclick);
    }

    View.OnTouchListener pinyinclick = new View.OnTouchListener() {// 右边字母条的点击事件

        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_MOVE:
//                    Logger.e("lintest", "+++++++++++ACTION_DOWN or ACTION_MOVE");
//                    Logger.e("lintest", "lastPosition===" + lastSelect);
                    locakScroll = true;
                    capitalListView.setBackgroundColor(0x10787878);
//                    ImageLoader.getInstance().lock();
                    int y = (int) event.getY();
                    int position = capitalListView.pointToPosition(0, y);
                    if (position == -1)
                        break;
                    if (position == lastSelect)
                        break;
                    if (lastSelect >= 0
                            && lastSelect < capitalListView.getChildCount()) {
                        TextView lastView = (TextView) capitalListView
                                .getChildAt(lastSelect);
                        lastView.setBackgroundResource(0);
                    }
                    lastSelect = position;
                    TextView view = (TextView) capitalListView.getChildAt(position);
                    if (view == null)
                        break;
                    view.setBackgroundColor(0xffcce4ff);
                    tvToast.setText(view.getText());
                    tvToast.setVisibility(View.VISIBLE);
                    handler.removeMessages(100);
                    Message msg = handler.obtainMessage();
                    msg.what = 100;
                    handler.sendMessageDelayed(msg, 1000);
                    lastSelect = position;
                    int id = 65 + position;
                    if (id >= 65 && id <= 90) {
                        position = cAdapter.getSortKeyPosition(id);
                        if (position >= 0) {
                            lv.setSelection(position);
                        }
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    stop();
//                    Logger.e("lintest", "+++++++++++ACTION_UP");
//                    Logger.e("lintest", "lastPosition===" + lastSelect);
                    break;
            }
            return true;
        }

        public void stop() {
//            ImageLoader.getInstance().unlock();
            capitalListView.setBackgroundColor(0);
        }
    };

    @Override
    public void initData() {
        super.initData();
        usersBeans_origin = (ArrayList<People>) getIntent().getExtras().getSerializable("persons");

        kjdb = KJDB.create(aty);
        datas = (ArrayList<People>) kjdb.findAllByWhere(People.class,
                "hospId=" + PreferenceHelper.readInt(aty, AppConfig.USER_INFO, AppConfig.HOSPITALID));
        if (datas != null && datas.size() > 0) {
            refresh(datas);
        } else {
            initDataP();
        }
    }

    void initDataP() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("usePinyinOrder", "1");
        params.put("pageSize", "-1");
        presenter.getPeopleDatas(params);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnSearchClear: // 点击清除
                etSearch.setText("");
                break;
            case R.id.addmember_sure_btn:
                Bundle bundle = new Bundle();
                Intent intent = new Intent();
                bundle.putSerializable("persons", cAdapter.getArrayList());
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
                break;
            case R.id.back:
                finish();
                break;
        }
    }

    @Override
    public void showPeopleDatas(PeopleBean peopleBean) {
        Message msg = new Message();
        msg.what = 999;
        handler.sendMessage(msg);
        datas = peopleBean.getDatas();
        refresh(peopleBean.getDatas());
        kjdb.deleteByWhere(People.class, "");
        kjdb.save(peopleBean.getDatas());
    }

    private void refresh(ArrayList<People> peoples) {
        ArrayList<People> showPeople = new ArrayList<>();
        for(People people : peoples){
            if(people.getHospId() == PreferenceHelper.readInt(aty, AppConfig.USER_INFO, AppConfig.HOSPITALID)){
                showPeople.add(people);
            }
        }

        if (cAdapter == null) {
            cAdapter = new AddMemberAdapter(this, showPeople, usersBeans_origin, handler, 1, lv, 0);
            lv.setAdapter(cAdapter);
        } else {
            cAdapter.setData(showPeople);
        }
        setGridView();

        emptyLayout.dismiss();
    }

    private void setGridView() {
        int size = cAdapter.getArrayList().size();

        if (size > 0) {
            addmember_sure_btn.setText("确认(" + size + ")人");
        } else {
            addmember_sure_btn.setText("确认");
        }

        int length = 80;

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 4) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
        grid.setLayoutParams(params); // 重点
        grid.setColumnWidth(itemWidth); // 重点
        grid.setHorizontalSpacing(5); // 间距
        grid.setStretchMode(GridView.NO_STRETCH);
        grid.setNumColumns(size); // 重点

        List<DepartOrPeopleData> datas = new ArrayList<>();
        for (People people : usersBeans_origin) {
            DepartOrPeopleData data = new DepartOrPeopleData();
            data.setDataId(people.getUserId() + "");
            data.setDataName(people.getUserName());
            datas.add(data);
        }

        adapter = new CreateGroupAdapter(grid, datas, R.layout.item_send_addmember);
        grid.setAdapter(adapter);

    }
}
